package com.phb.puhuibao.web.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.idp.pub.entity.Pager;
import com.idp.pub.service.IBaseService;
import com.idp.pub.web.controller.BaseController;
import com.phb.puhuibao.entity.MuserJobRelease;
import com.phb.puhuibao.entity.PhbNumber;
import com.phb.puhuibao.job.DistCnvter;
import com.phb.puhuibao.job.GetLatAndLngByBaidu;
import com.phb.puhuibao.job.GetLocation;
import com.phb.puhuibao.service.MuserJobReleaseService;
import com.idap.clinic.entity.UploadFile;
import com.idap.web.common.controller.Commons;

@Controller
@RequestMapping(value = "/muserJobRelease")
public class MuserJobReleaseController extends BaseController<MuserJobRelease, String> {

	@Resource(name = "muserJobReleaseService")
	public void setBaseService(IBaseService<MuserJobRelease, String> baseService) {
		super.setBaseService(baseService);
	}

	@Resource(name = "uploadFileService")
	private IBaseService<UploadFile, String> uploadFileService;
	
	@Resource(name = "phbNumberService")
	private IBaseService<PhbNumber, String> phbNumberService;
	@Resource(name = "commons")
	private Commons commons;

	@Resource(name = "muserJobReleaseService")
	private MuserJobReleaseService muserJobReleaseService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	/**
	 * 添加（职位发布）
	 * 
	 * @param mUserId
	 *            用户id
	 * @param jobTitle
	 *            职位标题
	 * @param jobDescribe
	 *            职位描述
	 * @param jobSalary
	 *            薪资待遇
	 * @param uploadPhoto
	 *            上传照片
	 * @param jobAddress
	 *            创建地址
	 * @param detailAddress
	 *            详细地址
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws JSONException
	 */
	@RequestMapping(value = "SaveJob")
	@ResponseBody
	public Map<String, Object> SaveJob(@RequestParam int mUserId, @RequestParam String jobTitle,
			@RequestParam String jobDescribe, @RequestParam String gender, @RequestParam String jobSalary,
			@RequestParam String salaryUnit, @RequestParam String jobEndDate, @RequestParam String longt,
			@RequestParam String lat, @RequestParam String detailAddress, @RequestParam String jobType,
			@RequestParam String jobClasstype, @RequestParam String jobTypeType)
			throws ParseException, IOException, JSONException {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			MuserJobRelease entity = new MuserJobRelease();
			GetLatAndLngByBaidu getLatAndLng = new GetLatAndLngByBaidu();
			GetLocation getLocation = new GetLocation();
			entity.setmUserId(mUserId);// 用户id
			entity.setJobTitle(jobTitle);// 职位标题
			entity.setJobDescribe(jobDescribe);// 职位描述
			entity.setGender(Integer.parseInt(gender));// 相别
			entity.setJobSalary(Integer.parseInt(jobSalary));// 薪资
			entity.setSalaryUnit(Integer.parseInt(salaryUnit));// 薪资单位
			entity.setJobEndDate(jobEndDate);// 结束时间
			BigDecimal a = new BigDecimal(longt);
			entity.setLongt(a.setScale(6, BigDecimal.ROUND_DOWN).doubleValue());// 经度
			BigDecimal b = new BigDecimal(lat);
			entity.setLat(b.setScale(6, BigDecimal.ROUND_DOWN).doubleValue());// 纬度
	
			String address = getLocation.getAddress(longt, lat);
			org.json.JSONObject object = new org.json.JSONObject(address);// 转换成json格式
			org.json.JSONObject result1 = new org.json.JSONObject(object.getString("result"));// 转换成json格式
																								// 拿到result
			org.json.JSONObject result2 = new org.json.JSONObject(result1.getString("addressComponent"));// 拿到addressComponent
			String city = result2.getString("city");// 市
			String district = result2.getString("district");// 区
			entity.setJobAddress(city + district);
	
			entity.setDetailAddress(detailAddress);// 详细地址
			entity.setJobType(Integer.parseInt(jobType));// 0.个人1.企业线上2.企业线下
			entity.setStatus(1);
			entity.setImportant(1);
			entity.setJobClasstype(Integer.parseInt(jobClasstype));// 兼职类型
			entity.setJobTypeType(Integer.parseInt(jobTypeType));// 1.体验2.互动3.分享4.校园5.个人
			entity.setAccessAmount(1);// 添加时默认第一次访问量为1
			MuserJobRelease ajob = this.getBaseService().save(entity);
			int jobId = ajob.getJobId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("jobId",jobId );
			data.put("result",params );
			data.put("message", "保存成功！");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 保存照片（个人职位发布）
	 * 
	 * @param jobId
	 *            职位id
	 * @param fileId
	 *            照片id
	 * @return
	 */
	@RequestMapping(value = "saveJobReleasePhoto")
	@ResponseBody
	public Map<String, Object> saveJobReleasePhoto(@RequestParam String jobId, @RequestParam String uploadPhoto) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			MuserJobRelease entity = new MuserJobRelease();
			entity.setJobId(Integer.parseInt(jobId));
			entity.setUploadPhoto(uploadPhoto);
			MuserJobRelease update = this.getBaseService().update(entity);
			data.put("message", "保存成功！");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("message", "出错！");
			data.put("status", 0);
			return data;
		}
		return data;
	}

	/**
	 * 获取企业照片
	 * 
	 * @param jobId
	 * @return
	 */
	@RequestMapping(value = "getJobUploadPhoto")
	@ResponseBody
	public Map<String, Object> getJobUploadPhoto(@RequestParam String jobId) {
		Map<String, Object> data = new HashMap<String, Object>();
		MuserJobRelease muserJobRelease = this.getBaseService().getById(jobId);
		String uploadPhoto = muserJobRelease.getUploadPhoto();
		List<UploadFile> params = new ArrayList<UploadFile>();
		try {
			if (StringUtils.isNotEmpty(uploadPhoto)) {
				String[] Photo = uploadPhoto.split(",");
				for (int i = 0; i < Photo.length; i++) {
					UploadFile uploadPhotoFile = uploadFileService.getById(Photo[i]);
					params.add(uploadPhotoFile);
				}
			}
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);
			return data;
		}
		data.put("result", params);
		data.put("message", "查询成功");
		data.put("status", 1);
		return data;
	}

	/**
	 * 删除(职位发布)
	 * 
	 * @param jobId
	 * @return
	 */
	@RequestMapping(value = "DelectJob")
	@ResponseBody
	public Map<String, Object> DeleteJob(@RequestParam int jobId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("jobId", jobId);
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			this.getBaseService().delete(params);
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);
			return data;
		}
		data.put("message", "删除成功！");
		data.put("status", 1);
		return data;
	}

	/**
	 * 修改(个人职位发布)
	 * 
	 * @param
	 * @return
	 *//*
		 * @RequestMapping(value = "UpdateJob")
		 * 
		 * @ResponseBody public Map<String, Object> UpdateJob(@RequestParam int
		 * jobId) { MuserJobRelease entity = new MuserJobRelease();
		 * entity.setJobId(jobId); Map<String, Object> data = new
		 * HashMap<String, Object>(); try {
		 * this.getBaseService().update(entity); } catch (Exception e) {
		 * data.put("message", "网络异常！"); data.put("status", 0); return data; }
		 * data.put("message", "修改成功！"); data.put("status", 1); return data; }
		 */
	/**
	 * (首页推荐职位(1线上职位 2 日结兼职  3高薪兼职  4附近职位))type不写就是推荐职位
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getConditionQuery")
	@ResponseBody
	public Map<String, Object> getConditionQuery(@RequestParam String pageno,@RequestParam String longt,
												 @RequestParam String lat,@RequestParam String type) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = muserJobReleaseService.getAJob(type, pageno, longt, lat);
			if (!list.isEmpty()) {
				data.put("result", list);
				data.put("message", "查询成功");
				data.put("status", 1);
			} 
			else {
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (Exception e) {
			data.put("message", "网络异常!");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 查询(个人职位发布)
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "QueryJob")
	@ResponseBody
	public Map<String, Object> QueryJob(@RequestParam int jobId, @RequestParam String mUserId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("jobId", jobId);
		params.put("mUserId", mUserId);
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			MuserJobRelease muserJobRelease = this.getBaseService().unique(params);
			data.put("massage", "查询成功");
			data.put("status", 1);
			data.put("reslut", muserJobRelease);
		} catch (Exception e) {
			data.put("massage", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 访问量(职位发布)
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "AddAccessAmount")
	@ResponseBody
	public Map<String, Object> AddAccessAmount(@RequestParam int jobId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("jobId", jobId);
		MuserJobRelease muserJobRelease = this.getBaseService().unique(params);
		MuserJobRelease entity = new MuserJobRelease();
		entity.setJobId(muserJobRelease.getJobId());
		entity.setAccessAmount(muserJobRelease.getAccessAmount() + 1);
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			this.getBaseService().update(entity);
			data.put("massage", "修改成功");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("massage", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 根据地址获得经纬度(职位发布)
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getLatLong")
	@ResponseBody
	public Map<String, Object> getLatLong(@RequestParam String Address) {
		GetLatAndLngByBaidu getLatAndLngByBaidu = new GetLatAndLngByBaidu();
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			Object[] o = getLatAndLngByBaidu.getCoordinate(Address);
			data.put("reslut", o);
			data.put("massage", "查询成功");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("massage", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 根据经纬度获得地址(职位发布)
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getLocationAddress")
	@ResponseBody
	public Map<String, Object> getLocationAddress(@RequestParam String log, @RequestParam String lat) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			GetLocation getLocation = new GetLocation();
			String address = getLocation.getAddress(log, lat);

			org.json.JSONObject object = new org.json.JSONObject(address);// 转换成json格式
			String result = object.getString("result");// 拿到result

			org.json.JSONObject result1 = new org.json.JSONObject(result);// 转换成json格式
			String addressComponent = result1.getString("addressComponent");// 拿到addressComponent

			org.json.JSONObject result2 = new org.json.JSONObject(addressComponent);
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();

			String province = result2.getString("province");// 省
			String city = result2.getString("city");// 市
			String district = result2.getString("district");// 区
			String street = result2.getString("street");// 街道

			Map<String, String> map = new HashMap<String, String>();
			map.put("province", province);
			map.put("city", city);
			map.put("district", district);
			map.put("street", street);
			list.add(map);

			data.put("reslut", list);
			data.put("massage", "查询成功");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("massage", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 全部兼职
	 * 
	 * @param pageno
	 * @param mUserId
	 * @param jobClasstype 职位类型
	 * @param salaryUnit 薪资单位
	 * @param longt 经度
	 * @param lat 纬度
	 * @param city 城市
	 * @param area 区县
	 * @param type 1最热2最近
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "getAllJob")
	@ResponseBody
	public Map<String, Object> getAllJob(@RequestParam String pageno,          @RequestParam String jobClasstype, 
										   @RequestParam String salaryUnit,   @RequestParam String longt,        
										   @RequestParam String lat,          @RequestParam String city,
										   @RequestParam String area,         @RequestParam String type) throws IOException {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = muserJobReleaseService.getAllparttime(pageno, jobClasstype, salaryUnit, longt, lat, city, area, type);		
			if(!list.isEmpty()){
				data.put("result", list);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else{
				data.put("message", "数据为空！");
				data.put("status", 2);		
			}
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 首页推荐(名企推荐)(职位发布)
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "companyRecommend")
	@ResponseBody
	public Map<String, Object> companyRecommend(@RequestParam String longt,@RequestParam String lat) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = muserJobReleaseService.getCompanyRecommend(longt, lat);
			if (!list.isEmpty()) {
				data.put("result", list);
				data.put("count", list.size());
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("result", list);
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (Exception e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 职位详情
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getPositionDetails")
	@ResponseBody
	public Map<String, Object> getPositionDetails(@RequestParam String jobId) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			MuserJobRelease muserJobRelease = this.getBaseService().getById(jobId);
			String uploadPhoto = muserJobRelease.getUploadPhoto();// 获得照片
			List<String> list1 = new ArrayList<String>();
			if (StringUtils.isNotEmpty(uploadPhoto)) {
				String[] Photo = uploadPhoto.split(",");
				for (int i = 0; i < Photo.length; i++) {
					UploadFile uploadPhotoFile = uploadFileService.getById(Photo[i]);
					list1.add(uploadPhotoFile.getFilePath());//;photoPaths
				}
			}
			Map<String, Object> data2 = new HashMap<String, Object>();
			MuserJobRelease entity = new MuserJobRelease();
			entity.setJobId(Integer.parseInt(jobId));
			List<Map<String, Object>> jobDetails = muserJobReleaseService.getJobDetails(entity);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("jobId", jobId);
			params.put("mUserId", entity.getmUserId());
			 List<PhbNumber> list= phbNumberService.findList(params);
			if(list.size()>0){
				data2.put("statusForUser", list.get(0).getStatus());
			}else{
				data2.put("statusForUser", -1);

			}
			data2.put("jobDetails", jobDetails);
			data2.put("uploadPhoto", list1);
			data.put("result", data2);
			data.put("message", "查询成功");
			data.put("status", 1);
		} catch (DataAccessException e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}

	/**
	 * 
	 * 获得首页条件查询图片及汉字
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getFirstPagePhoto")
	@ResponseBody
	public Map<String, Object> getFirstPagePhoto() {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> retobj = null;
		List<Map<String, Object>> list = null;
		String sql = "SELECT p.activity,p.ad_name,p.image FROM phb_advertisement p WHERE p.status=3";
		try {
			list = this.jdbcTemplate.queryForList(sql);
			if (!list.isEmpty()) {
				data.put("result", list);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("result", list);
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (DataAccessException e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}
	/**
	 * 
	 * 获得所有薪资单位
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "getSettlementName")
	@ResponseBody
	public Map<String, Object> getSettlementName() {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> retobj = null;
		List<Map<String, Object>> list = null;
		String sql = "SELECT a.id settlementId,a.settlement_name settlementName from phb_settlement_method a";
		try {
			list = this.jdbcTemplate.queryForList(sql);
			if (!list.isEmpty()) {
				data.put("result", list);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("result", list);
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (DataAccessException e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}
	//-----我的职位(0报名这1发布职位)-----
	@RequestMapping(value = "getMuserJobs")
	@ResponseBody
	public Map<String, Object> getMuserJobs(@RequestParam String mUserId,@RequestParam String longt,
													@RequestParam String lat,@RequestParam String type,
													@RequestParam String pageno) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> releaseJobs = muserJobReleaseService.getReleaseJobs(mUserId, longt, lat, type, pageno);	
			if (!releaseJobs.isEmpty()) {
				data.put("result", releaseJobs);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (DataAccessException e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}
	//-----搜索关键字-----
	@RequestMapping(value = "getSearchKeywords")
	@ResponseBody
	public Map<String, Object> getSearchKeywords(@RequestParam String Keywords,@RequestParam String pageno) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> SearchKeywords= muserJobReleaseService.getKeywords(Keywords,pageno);
			if (!SearchKeywords.isEmpty()) {
				data.put("result", SearchKeywords);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (DataAccessException e) {
			data.put("message", "网络异常");
			data.put("status", 0);
		}
		return data;
	}	
	//-----搜索关键字/根据热门搜索查询（兼职类型）-----
	@RequestMapping(value = "getSearchKeywordsJobs")
	@ResponseBody
	public Map<String, Object> getSearchKeywordsJobs(@RequestParam String Keywords,@RequestParam String longt,
														 @RequestParam String parttimeJobTypeId,
														 @RequestParam String lat,@RequestParam String pageno) {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> KeywordsQureyJobs= muserJobReleaseService.getKeywordsQureyJobs(Keywords,parttimeJobTypeId, pageno, longt, lat);
			if (!KeywordsQureyJobs.isEmpty()) {
				data.put("result", KeywordsQureyJobs);
				data.put("message", "查询成功");
				data.put("status", 1);
			}else {
				data.put("message", "数据为空");
				data.put("status", 2);
			}
		} catch (DataAccessException e) {
				data.put("message", "网络异常");
				data.put("status", 0);
		}
		return data;
	}
		
		//职位下架
		@RequestMapping(value = "JobInvalid")
		@ResponseBody
		public Map<String, Object> JobInvalid(@RequestParam String mUserId,@RequestParam String jobId) {
			Map<String, Object> data = new HashMap<String, Object>();
			Map<String, Object> params = new HashMap<String, Object>();
			try {		
					params.put("jobId", jobId);
					params.put("mUserId", mUserId);
					MuserJobRelease job = this.getBaseService().unique(params);
					if(job!=null){
						MuserJobRelease entity=new MuserJobRelease();
						entity.setJobId(job.getJobId());
						entity.setStatus(0);
						this.getBaseService().update(entity);
					data.put("message", "下架成功");
					data.put("status", 2);
					}else{
						data.put("message", "下架失败");
						data.put("status", 1);
					}
					
			} catch (Exception e) {
					data.put("message", "网络异常");
					data.put("status", 0);
			}
			return data;
		}	
}
